/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
// import modelBody from "../../salesinfo/sales_contract/salesContract.vue";
import modelBody from "../../salesinfo/sales/sales.vue";
// import modelHeader from "../../inventoryinfo/goodsin_class/goodsInCom.vue"
import modelHeader from "../../inventoryinfo/goods_inventory_warehouse_xm/goodsInventoryWarehouse_xm.vue"
import gridHeader from "@/components/print/selectTemplet.vue"
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: modelBody,
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    async onInit() { //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      this.queryFields = ["Client_name", "CreateDate"]
      let startTime = this.base.getOneWeekAgoDate()
      let endTime = this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]
      this.detailOptions.textInline = false
      this.textInline = false
      // this.setFiexdSearchForm(true);
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      if (this.$route.path == "/q_after_delivery" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        //  try {
        //   this.searchFormFields.Voucher_sub = null
        //   this.searchFormFields.Sales_contract_sub = null
        //   this.searchFormFields.Site = null
        //   this.searchFormFields.WHSE_Id = null
        //   this.searchFormFields.AuditStatus = null
        //   this.searchFormFields.Goods_num = [null, null]
        //   this.searchFormFields.Total_price = [null, null]
        //   this.searchFormFields.CreateDate = [null, null]
        //  } catch (error) {
        //   console.log("error",error)
        //  }
        //   const selectList = ['WHSE_Id','AuditStatus', 'CreateDate']
        //   this.searchFormOptions.forEach(item => {
        //     item.forEach(x => {
        //       if (selectList.includes(x.field)) {

        //         x.onChange = (v) => {
        //           this.$route.query = {}
        //         }
        //       }
        //     })
        //   })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      if (this.$route.path != "/q_after_delivery"){
        this.setFiexdSearchForm(true);
        this.height = 550 - 150;
        this.buttons.forEach(item => {
          if (item.value != "Search") {
            item.hidden = true
          }
        })
      }
      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      this.detailOptions.buttons.unshift({
        name: "选择配件",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {
          if (this.rowschild && this.$refs.detail.rowData.length) {
            this.rowschild.click()
          }

          this.$store.commit("setTabelText", true)
          if (!this.editFormFields.WHSE_no) {
            this.base.ElMessageFn("请先选择出库机构")
            return false;
          }
          // else if (!this.editFormFields.Tax_rate) {
          //   this.base.ElMessageFn("请先选择税率")
          //   return false;
          // }
          this.$refs.modelHeader.open(this.editFormFields.WHSE_no)
        }
      })
      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_after_delivery" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
          return false
        }
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        this.rowschild = rows[0].childNodes[2]
        setTimeout(() => {
          // 数量
          let testInputDom = rows[index].querySelectorAll("td")[7].querySelector("input")
          testInputDom.addEventListener("keyup", (e) => {
            if (!(+e.target.value > 0)) {
              row.Total_price = ""
              // row.Tax_exclusive_exWarehouse_total_price = ""//无税总价
              return this.base.ElMessageFn("数量请输入有效正数")
            }
            if (!(+row.Goods_price >= 0) && +row.Goods_price != 0) {
              return this.base.ElMessageFn("单价请输入有效数字")
            }
            row.Total_price = this.base.roundToFourDecimals(e.target.value * row.Goods_price)
            row.Cost_price_total_price = this.base.roundToFourDecimals(e.target.value * row.CostPrice) //成本总价
            row.Tax_exclusive_total_price = this.base.roundToFourDecimals(e.target.value * row.Tax_exclusive) //无成本总价

            //无税总价
            // if (this.editFormFields.Tax_rate) {
            //   let wsjg = row.Goods_price / (1 + +this.editFormFields.Tax_rate)
            //   let num = wsjg * e.target.value
            //   row.Tax_exclusive_exWarehouse_total_price = this.base.roundToFourDecimals(num)
            // }
          })
          // 单价
          let testInputDom2 = rows[index].querySelectorAll("td")[8].querySelector("input")
          testInputDom2.addEventListener("keyup", (e) => {
            if (!(+e.target.value >= 0) && +e.target.value != 0) {
              row.Total_price = ""
              // row.Tax_exclusive_exWarehouse_total_price = ""
              return this.base.ElMessageFn("单价请输入有效数字")
            }
            if (!(+row.Goods_num >= 0)) {
              return this.base.ElMessageFn("数量请输入有效数字")
            }
            row.Total_price = this.base.roundToFourDecimals(e.target.value * row.Goods_num)
            // //无税总价
            // if (this.editFormFields.Tax_rate) {
            //   let wsjg = e.target.value / (1 + +this.editFormFields.Tax_rate)
            //   let num = wsjg * row.Goods_num
            //   row.Tax_exclusive_exWarehouse_total_price = this.base.roundToFourDecimals(num)
            // }
          })
        })
        return true
      }
    },
    WHSE_IdDisableFn() {
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == 'WHSE_no') {
            x.disabled = true
          }
        })
      })
    },
    async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path == "/q_after_delivery" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Fittings_delivery", param)
        // const sectionState = ["[null,null]", JSON.stringify(["", null]), JSON.stringify([null, ""]), JSON.stringify(["", ""])]
        // const numState = sectionState.includes(JSON.stringify(this.searchFormFields.Goods_num))
        // const numState2 = sectionState.includes(JSON.stringify(this.searchFormFields.Total_price))
        // const dateState = sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Voucher_sub ||this.searchFormFields.Sales_contract_sub ||this.searchFormFields.Site || !numState || !numState2 || !dateState) {
        //   param.wheres = param.wheres.filter(item => item.name != "Fittings_delivery")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return this.testAdd(formData);
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return this.testAdd(formData);
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => {
        return x.AuditStatus == 1
      });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    rowClick({
      row,
      column,
      event
    }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    delDetailRow(rows) { //弹出框删除明细表的行数据(只是对table操作，并没有操作后台)
      if (this.currentAction != 'Add') return true;
      try {
        if (rows.length == this.$refs.detail.rowData.length) {
          this.$store.commit("setWHSE_time", true)
          this.$store.commit("setWHSE_disabled", true)
          this.WHSE_Interval = setInterval(() => {
            console.log("WHSE_Interval", this.WHSE_Interval)
            this.editFormOptions.forEach(item => {
              item.forEach(x => {
                if (x.field == 'WHSE_no') {
                  if (this.$store.state.WHSE_disabled) {
                    x.disabled = true
                  } else {
                    x.disabled = false
                  }
                }
              })
            })
            if (!this.$store.state.WHSE_time) {
              clearInterval(this.WHSE_Interval)
              console.log("WHSE_Interval清除", this.WHSE_Interval)

            }
          }, 500)

        }
      } catch {
        console.log("删除catch", )
      }
      return true;
    },
    detailRowClick({
      row,
      column,
      event
    }) {
      //编辑弹出框从表table点击行选中当前行，没有从表的不用管
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_after_delivery" || this.rowAuditStatus != 0) {
        return
      } //|| !this.CreateUserBoole
      if (column.property == "Goods_num" || column.property == "Remark" || column.property == "Goods_price") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_after_delivery" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      if (this.currentAction == "Add") {
        this.editFormFields.Goods_num = 0
        this.editFormFields.Total_price = 0
      }
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == 'Image' || x.field == 'Attachment') {
            //启用多图上传(默认单图)
            x.multiple = true;
            //最多可以上传3张照片
            x.maxFile = 3;
          }
          if (x.field == "Sales") {
            x.hidden = true
          }
          // if (x.field == "Tax_rate") {
          //   x.onChange = (e) => {
          //     let detailDate = this.$refs.detail.rowData
          //     detailDate.forEach(o => {
          //       //无税出库金额总价
          //       if (+o.Goods_num && o.Goods_num && o.Goods_price && +o.Goods_price) {
          //         let num = (o.Goods_num * o.Goods_price) / (1 + +e)
          //         o.Tax_exclusive_exWarehouse_total_price = this.base.roundToFourDecimals(num)
          //       } else {
          //         o.Tax_exclusive_exWarehouse_total_price = ""

          //       }
          //     })
          //   }
          // }
          if (x.field == "Sales_sub" || x.field == "Voucher_sub" || x.field == "Goods_num" || x.field == "Total_price" || x.field == "Site" || x.field == "Client_name") {
            x.disabled = true
            if (x.field == "Sales_sub" && this.currentAction == 'Add') {
              x.remote = true
              x.extra = {
                icon: "el-icon-zoom-in",
                text: "选择销售单",
                style: "color:#3a8ee6;font-size:13px;cursor:default",
                click: () => {
                  this.$refs.modelBody.open()
                }
              }
            } else {
              x.extra = null
            }
          } else {
            x.disabled = false
          }
          if (x.field == 'WHSE_no') {
            const bool = !(this.currentAction == 'Add')
            x.disabled = bool
          }
          if (this.$route.path != "/q_after_delivery" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
            if (x.field == "Sales_sub") {
              x.remote = true
              x.extra = null
            }
          }
        })
      })
    },
    testAdd(formData) {
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      let boole = formData.detailData.some(item => item.Goods_num === "" || item.Goods_num === null || item.Goods_num === undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写数量")
        return false;
      }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0 && (item.Goods_num != "" || item.Goods_num != null || item.Goods_num == undefined))
      if (boole2) {
        this.base.ElMessageFn("明细表中数量不可为零或空")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中数量请填写有效正数")
        return false;
      }
      let boole4 = formData.detailData.some(item => item.AvailableQuantity < item.Goods_num)
      if (boole4) {
        this.base.ElMessageFn("明细表中数量不可大于可用数量")
        return false;
      }

      // let boole1 = formData.detailData.some(item => item.Goods_price === "" || item.Goods_price === null || item.Goods_price === undefined)
      // if (boole1) {
      //   this.base.ElMessageFn("明细表中请填写单价")
      //   return false;
      // }
      // let boole22 = formData.detailData.some(item => +item.Goods_price === 0 &&(item.Goods_price!=""||item.Goods_price!=null|| item.Goods_price == undefined))
      // if (boole22) {
      //   this.base.ElMessageFn("明细表中单价不可为零或空")
      //   return false;
      // }
      //   let boole33 = formData.detailData.every(item => +item.Goods_price > 0 && +item.Goods_price)
      //   if (!boole33) {
      //     this.base.ElMessageFn("明细表中单价请填写有效正数")
      //     return false;
      //   }
      let boole1 = formData.detailData.some(item => item.Goods_price === "" || item.Goods_price === null || item.Goods_price === undefined)
      if (boole1) {
        this.base.ElMessageFn("明细表中请填写单价")
        return false;
      }
      let boole22 = formData.detailData.every(item => item.Goods_price !== "" || item.Goods_price !== null || item.Goods_price === undefined || item.Goods_price ? ("" + item.Goods_price).trim() !== "" : +item.Goods_price)
      if (!boole22) {
        this.base.ElMessageFn("明细表中单价不可为空")
        return false;
      }
      let boole33 = formData.detailData.every(item => +item.Goods_price >= 0)
      if (!boole33) {
        this.base.ElMessageFn("明细表中单价请填写有效正数")
        return false;
      }
      return true
    },
  }
};
export default extension;